<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Hash;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    const POSTONLY = ['name','password','mobile','role_id','company_id'];

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'password',
        'mobile',
        'role_id',
        'company_id',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'status' => 'boolean',
    ];

    protected $appends = [
        'status_text'
    ];

    public function getStatusTextAttribute()
    {
        return $this->status ? '启用' : '禁用';
    }

    /**
     * 验证用户的密码以获得 Passport 密码授权。
     *
     * @param  string  $password
     * @return bool
     */
    public function validateForPassportPasswordGrant($password)
    {
        return Hash::check($password, $this->password);
    }

    protected function serializeDate(\DateTimeInterface $date)
    {
        return $date->format($this->dateFormat ?: 'Y-m-d H:i:s');
    }

    // role
    public function role()
    {
        return $this->belongsTo(Role::class)->select('id','name','auth');
    }

    public function projects()
    {
        return $this->belongsToMany(Project::class,'project_users');
    }

    public function disclosures()
    {
        return $this->belongsToMany(Disclosure::class,'disclosure_users');
    }

    public function company()
    {
        return $this->hasOne(Company::class,'id','company_id')->select('id','title','logo');
    }

    public function safes()
    {
        return $this->hasMany(Safe::class,'person_id','id')->select('id','title');
    }

    public function schedules()
    {
        return $this->hasMany(Schedule::class,'person_id','id')->select('id','title');
    }

    public function qualitys()
    {
        return $this->hasMany(Quality::class,'person_id','id')->select('id','title');
    }

    public function temps()
    {
        return $this->hasMany(TempInspect::class,'person_id','id')->select('id','title');
    }

}
